package taglib;

import java.text.NumberFormat;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import utils.NumberUtils;

@SuppressWarnings("serial")
public class NumberFormatTag extends TagSupport {

	private String style;
	private String value;
	private Integer minimumFractionDigits = 0;
	private Integer maximumFractionDigits = 2;
	public int doStartTag()  {
		return (SKIP_BODY);
	}
	
	public int doEndTag()  {
		
		String output = "";
		if(StringUtils.isNotEmpty(value)){
			if("percent".equals(style)){
				NumberFormat  nf = NumberFormat.getPercentInstance();
				nf.setMinimumFractionDigits(minimumFractionDigits);
				nf.setMaximumFractionDigits(maximumFractionDigits);
				output = nf.format(Double.parseDouble(value));
			}
			else if("currency".equals(style)){
				NumberFormat  nf = NumberFormat.getCurrencyInstance();
				nf.setMinimumFractionDigits(minimumFractionDigits);
				nf.setMaximumFractionDigits(maximumFractionDigits);
				output = nf.format(Double.parseDouble(value));
			}
			else{
				output = NumberUtils.format(value, maximumFractionDigits);
			}
		}
		
		
		
		try {
			JspWriter writer = pageContext.getOut();
			writer.print(output);
		} catch (Exception e) {
			
		}
		return (SKIP_BODY);
	}

	
	public static void main(String[] args){
		NumberFormat  nf = NumberFormat.getCurrencyInstance();
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		String s = nf.format(Double.parseDouble("333.333"));
		System.out.println(s);
	}

	public Integer getMaximumFractionDigits() {
		return maximumFractionDigits;
	}

	public void setMaximumFractionDigits(Integer maximumFractionDigits) {
		this.maximumFractionDigits = maximumFractionDigits;
	}

	public Integer getMinimumFractionDigits() {
		return minimumFractionDigits;
	}

	public void setMinimumFractionDigits(Integer minimumFractionDigits) {
		this.minimumFractionDigits = minimumFractionDigits;
	}

	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}
